<template>
  <div class="yxp-course">
    <TopBack :title="title" :type="type" :id="id" :courseId="courseId" :course_type="course_type"  @point="handlePoint"/>
    <div class="yxp-scene-main">
      <div class="main-box" v-if="!isVoice && !isRead">
        <div class="main-box-item">
          <div class="content">
            <div class="content-wrap">
              <!-- <div class="content-wrap-box"> -->
              <h3 class="work-title">写作要求</h3>
              <div class="work-info" v-html="content.require"></div>
              <!-- </div> -->
            </div>
          </div>
        </div>
      </div>
      <div class="main-box" v-if="!isVoice && isRead">
        <div class="main-box-item">
          <div class="buffer" v-if="isBuffer">
              <div class="buffer-desc">
                <div class="buffer-desc-content">{{voiceResult}}</div>
              </div>
              <div class="buffer-item sec-item">
                <!-- <span v-for="(item,i) in buffer" :Key="'b' + i" :style="{height: Math.abs(item / 20) + 'px'}"></span> -->
                <div class="buffer-item-l">
                  <span v-show="voice >= 1"></span>
                  <span v-show="voice >= 2"></span>
                  <span v-show="voice >= 3"></span>
                  <span v-show="voice >= 4"></span>
                  <span v-show="voice >= 5"></span>
                  <span v-show="voice >= 6"></span>
                  <span v-show="voice >= 7"></span>
                  <span v-show="voice >= 8"></span>
                  <span v-show="voice >= 9"></span>
                  <span v-show="voice >= 10"></span>
                </div>
                <div class="buffer-item-r">
                  <span v-show="voice >= 1" ></span>
                  <span v-show="voice >= 2"></span>
                  <span v-show="voice >= 3"></span>
                  <span v-show="voice >= 4"></span>
                  <span v-show="voice >= 5"></span>
                  <span v-show="voice >= 6"></span>
                  <span v-show="voice >= 7"></span>
                  <span v-show="voice >= 8"></span>
                  <span v-show="voice >= 9"></span>
                  <span v-show="voice >= 10"></span>
                </div>
              </div>
              <!-- <div class="buffer-item bg-item">
                <span v-for="(item,i) in buffer" :Key="'b1' + i"></span>
              </div> -->
              <div class="buffer-btn" id="yxp-scene-btn7" @click="realTimeAsrStop">完成录音</div>
            </div>
              <div class="content">
                <div class="content-wrap scene-box">
                  <h3 class="work-title">写作要求</h3>
                  <div class="work-info" v-html="content.require"></div>
                </div>
                <div class="record" v-if="isShow" id="yxp-scene-btn6" @click="realTimeAsrOpen()">
                  <div class="record-item zh-item">
                    <img src="@/assets/composition/record-icon.png" />
                    <p class="record-item-text">使用中文描述</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
      <div class="main-box" v-if="isVoice">
        <!--两列-->
        <div :class="{'main-box-content': isModel, 'main-box-item': !isModel}">
          <div class="content">
            <div class="content-wrap scene-box">
              <h3 class="work-title">写作要求</h3>
              <div class="work-info" v-html="content.require"></div>
              <div class="content-des" v-if="isDetail">
                <h3 class="ask-title">我的描述</h3>
                <p class="info">{{voiceModel}}</p>
              </div>
            </div>
          </div>
          <div class="record">
                <div class="record-item first-item" id="yxp-scene-btn4" @click="realTimeAsrOpen">
                  <img src="@/assets/composition/record-icon.png" />
                  <p class="record-item-text">再来一次</p>
                </div>
                <div class="record-item"  id="yxp-scene-btn5" @click="isModel = true">
                  <img src="@/assets/composition/record-model.png" />
                  <p class="record-item-text">查看模型</p>
                </div>
            </div>
        </div>
        <div class="main-box-content" v-if="isModel">
          <div class="content">
            <div class="content-wrap">
              <div class="close" id="yxp-scene-btn3" @click="handleCloseModel"></div>
              <h3 class="model-title">模型</h3>
              <div class="model-info">
                <!-- <h3 class="date">周六 4月2号</h3> -->
                <template>
                <template v-if="articleType === 1 || articleType === 5">
                  <span v-html="zhHead"  :style="{display: 'block',color: '#333'}"></span>
                  <span v-for="(item,i) in zhText" :key="'z' + i" :style="{color: item.isColor}" v-html="item"></span>
                  <span v-html="zhEnd" :style="{float: 'right',overflow: 'hidden'}"></span>
                </template>
                <template v-else-if="articleType === 2">
                  <span v-html="zhHead"  :style="{display: 'block','text-align': 'center',color: '#333'}"></span>
                  <span v-for="(item,i) in zhText" :key="'z' + i" v-html="item"></span>
                  <span v-html="zhEnd" :style="{float: 'right',overflow: 'hidden'}"></span>
                </template>
                <template v-else-if="articleType === 3">
                  <span v-html="zhHead"  :style="{display: 'block','text-align': 'center',color: '#333'}"></span>
                  <span v-for="(item,i) in zhText" :key="'z' + i" v-html="item"></span>
                </template>
                <template v-else-if="articleType === 4">
                  <span v-html="zhHead" :style="{display: 'block',color: '#333'}"></span>
                  <span v-for="(item,i) in zhText" :key="'z' + i" v-html="item"></span>
                </template>
                <template v-else>
                  <span v-for="(item,i) in zhText" :key="'z' + i" v-html="item"></span>
                </template>
              </template>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>

    <div class="scene" v-if="!isVoice">
      <div class="scene-btn">
        <div class="scene-btn-item" id="yxp-scene-btn" @click="handleScene">
          <span v-if="!isShow">情景构建</span>
          <span v-if="isShow">中文表达</span>
          <img src="@/assets/word/no-next.png" v-if="!isShow"/>
        </div>
      </div>
    </div>
    <div class="scene" v-if="isVoice">
      <div class="scene-btn" id="yxp-scene-btn1" @click="handleNext">
        <div class="scene-btn-item">
          <span>表达对照</span>
          <img src="@/assets/word/no-next.png"/>
        </div>
      </div>
    </div>
    <div class="mark" v-if="isPoint"></div>
    <readPop :isPoint="isPoint" :content="content.analysis" @point="handlePoint" />
    <!-- <div class="buffer-wrap" v-if="isBuffer">
       <div class="buffer">
      <div class="buffer-desc">
        <div class="buffer-desc-content">{{voiceResult}}</div>
      </div>
      <div class="buffer-item">
        <div class="buffer-item-l">
          <span v-if="voice >= 1" ></span>
          <span v-if="voice >= 2"></span>
          <span v-if="voice >= 3"></span>
          <span v-if="voice >= 4"></span>
          <span v-if="voice >= 5"></span>
          <span v-if="voice >= 6"></span>
          <span v-if="voice >= 7"></span>
          <span v-if="voice >= 8"></span>
          <span v-if="voice >= 9"></span>
          <span v-if="voice >= 10"></span>
        </div>
        <div class="buffer-item-r">
          <span v-if="voice >= 1" ></span>
          <span v-if="voice >= 2"></span>
          <span v-if="voice >= 3"></span>
          <span v-if="voice >= 4"></span>
          <span v-if="voice >= 5"></span>
          <span v-if="voice >= 6"></span>
          <span v-if="voice >= 7"></span>
          <span v-if="voice >= 8"></span>
          <span v-if="voice >= 9"></span>
          <span v-if="voice >= 10"></span>
        </div>
      </div>
      <div class="buffer-btn" @click="realTimeAsrStop">完成录音</div>
    </div>
    </div> -->
    <Timetips ref="timetips"></Timetips>
  </div>
</template>
<script>
import Recorder from 'recorder-core'
import 'recorder-core/src/engine/mp3'
import 'recorder-core/src/engine/mp3-engine'
import TopBack from '../components/TopBack.vue'
import readPop from '../components/readPop.vue'
import Timetips from '@/components/Timetips.vue'
import storage from '@/utils/storage.js'
import { randWord } from '@/utils/rand.js'
export default {
  name: 'sceneIndex',
  components: {
    TopBack,
    readPop,
    Timetips
  },
  data () {
    return {
      asrData: [],
      recIsOpen: false,
      BSync: null,
      isController: false,
      title: '格式塔情景植入',
      content: '',
      courseId: '',
      id: '',
      course_type: 0,
      isShow: false,
      isPoint: false,
      isBuffer: false, // gai
      isVoice: false,
      isModel: true,
      isDetail: true,
      isRead: false, // gai
      zhText: [],
      DB: 0,
      voice: 0,
      socket: null,
     // isFinished: false,
      audio: "",
     // audioSrc: '',
     // recorder: new Record(),
      timer: null,
      type: '1',
       rec: null,
      wave: null,
      recBlob: null,
       recordTransformData: null,
      recordStarted: false,
      voiceResult: '',
      voiceModel: '',
      max_record: 0,
      result: '',
      articleType: 0,
      isStart: false,
      isAllow: false,
      buffer: [],
      sn: window.location.href
    }
  },
  watch: {
    DB (newDb) {
      console.log(newDb)
      if (+newDb === 0) {
        this.voice = 0;
      } else if (newDb >= 1 && newDb <= 20) {
        // 显示一格音谱
        this.voice = 1;
      } else if (newDb >= 21 && newDb <= 40) {
        this.voice = 2;
        // 显示二格音谱
      } else if (newDb >= 41 && newDb <= 60) {
        this.voice = 3;
        // 显示三格音谱
      } else if (newDb >= 71 && newDb <= 90) {
        this.c = 4;
        // 显示四格音谱
      } else if (newDb >= 91 && newDb <= 120) {
        this.voice = 5;
        // 显示五格音谱
      } else if (newDb >= 121 && newDb <= 140) {
        this.voice = 6;
        // 显示六格音谱
      } else if (newDb >= 141 && newDb <= 160) {
        this.voice = 7;
        // 显示七格音谱
      } else if (newDb >= 161 && newDb <= 180) {
        this.voice = 8;
        // 显示八格音谱
      } else if (newDb >= 181 && newDb <= 200) {
        this.voice = 9;
        // 显示九格音谱
      } else if (newDb > 200) {
        this.voice = 10;
        // 显示全部音谱
      }
    }
  },
  created () {
    this.BSync = window.isBSync()
    this.isController = window.isController()
    this.realTimeAsrInit()
    if (this.$route.query.id) {
      let { courseId, id, course_type } = this.$route.query
      this.courseId = +courseId
      this.id = +id
      this.course_type = +course_type
    }
    let data = storage.get('sceneData')
    if (data) {
      this.content = data
      this.max_record = parseInt(data.max_record)
      this.articleType = data.type
      let zhText = data.sentence_translation
      if (this.articleType === 1 || this.articleType === 5 || this.articleType === 2) {
        this.zhHead = zhText.splice(0,1).join('').replace('##','')
        this.zhEnd = zhText.pop()
        if (this.zhEnd.indexOf('##')) {
          this.zhEnd = this.zhEnd.replace('##','<br/>')
        }
      } else if (this.articleType === 3 || this.articleType === 4) {
        this.zhHead = zhText.splice(0,1).join('').replace('##','')
      }
      let zhArr = []
      zhText.map(item =>{
        if (item.indexOf('&&') !== -1 || item.indexOf('##') !== -1) {
          let val = item.replace('&&', '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;').replace('##','<br>')
          zhArr.push(val)
        } else {
          zhArr.push(item)
        }
      })
      this.zhText = zhArr
    }
  },
  beforeDestroy () {
    if (this.rec !== null) {
      this.realTimeAsrStop()
      this.rec = null
    }
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
  },
  methods: {
    handleScene () {
      this.isShow = true
      this.isRead = true
      this.type = '2'
    },
    initSocket () {
      let that = this
      this.socket = new WebSocket('wss://vop.baidu.com/realtime_asr?sn=21812587', 'websocket')
      console.log(this.socket)
      this.socket.addEventListener('open', this.socketOpen)
      if(this.isController){
        this.socket.addEventListener('message', (msgevt) => {
          msgevt.data && that.socketMessage(JSON.parse(msgevt.data))
        })
      }
      this.socket.addEventListener('close', this.socketClose)
    },
    realTimeAsrInit () {
      let that = this
      !this.rec && (this.rec = Recorder({
        type: 'mp3',
        sampleRate: 16000,
        bitRate: 16,
        bufferSize: 4096,
        onProcess: (buffers, powerLevel, bufferDuration, bufferSampleRate) => {
          this.recordTransformData = Recorder.SampleData(buffers, bufferSampleRate, 16000, {
            index: this.recordTransformData ? this.recordTransformData.index: 0,
            offset: this.recordTransformData ? this.recordTransformData.offset: 0.0,
          });
          // 业务处理-start
          let buffer = buffers[buffers.length-1]
          this.buffer = buffer
          var maxVal = 0;
          for (var i = 0; i < buffer.length; i++) {
              if (maxVal < buffer[i]) {
                  maxVal = buffer[i];
              }
          }
          this.DB = parseInt(maxVal / 100);
          // 业务处理-end
          this.socket.send(this.recordTransformData.data)
          if (bufferDuration / 1000 >= this.max_record) {
            this.asrSyncStopEvent()
          }
        }
      }))
      if(!that.isController){
        that.BSync && that.BSync.socket.on('sync:socket', function (data) {
          that.realTimeAsrMessage(data)
        })
        that.BSync && that.BSync.socket.on('sync:cmd', function (data) {
          console.log('==================', data, that.sn, '=========')
          if (data.sn === that.sn) {
            data.cmd && eval(`typeof ${data.cmd} == 'function' && ${data.cmd}(data)`)
          }
        })
      }
      this.realTimeAsrOpen(false)
    },
    _realTimeAsrOpen () {
      console.log('正在启动转写')
      let that = this
      this.socket = new WebSocket(`wss://vop.baidu.com/realtime_asr?sn=${new Date().getTime()}`, 'websocket')
      this.socket.addEventListener('open', () => {
        this.socket.send(JSON.stringify({
          "type": "START",
          "data": {
            "appid": 21812587,
            "appkey": "WzgLZY1Ico79HSU6fzzsG9Ic",
            "dev_pid": 15372,
            "cuid": "cuid-1",
            "format": "pcm",
            "sample": 16000
          }
        }))
        this.DB = 0
        this.isBuffer = true
        this.isVoice = false
        this.isModel = false
        this.rec.start()
      })
      if(that.isController){
        this.socket.addEventListener('message', (msgevt) => {
          let data = msgevt.data
          if(data){
            data = JSON.parse(data)
            if(data.err_no == 0){
              that.BSync && that.BSync.socket.emit('sync:socket', data)
              that.realTimeAsrMessage(data)
            }
          }
        })
      }
      this.socket.addEventListener('close', (e) => {
        console.log('关闭连接', e)
        this.asrSyncStopEvent()
      })
    },
    _realTimeAsrMessage (data) {// 业务处理
      console.log('业务处理.识别数据', data)
      this.voiceModel = data.join(' ')
      this.voiceResult = data.join(' ')
    },
    realTimeAsrMessage (data) {
      console.log('原始数据', data)
      this.asrData[this.asrData.length == 0 ? 0 : (this.asrData.length - 1)] = data.result
      if(data.type == 'FIN_TEXT'){
        this.asrData[this.asrData.length] = ''
      }
      this._realTimeAsrMessage(this.asrData)
    },
    asrSyncStopEvent () {
      let that = this
      // 传递关闭事件
      if(that.isController){
        that.BSync && that.BSync.socket.emit('sync:cmd', {
          cmd: 'that.realTimeAsrStop',
          sn: that.sn
        })
        that.realTimeAsrStop()
      }
    },
    realTimeAsrStop () {
      // 加锁
      if(this.recordTransformData){
        this.isBuffer = false
        this.isVoice = true
        this.isModel = true
        this.voiceResult = ''
        this.recordTransformData = null
        this.asrData = []
        this.isBuffer = false
        this.isVoice = true
        this.isModel = true
        this.voiceResult = ''
        console.log(this.rec)
        this.rec.stop((blob, duration) => {
          console.log(33, blob, duration)
        })
      }
    },
    realTimeAsrOpen (asr = true) {
      if (this.isAllow) {
        this.$toast('请先打开麦克风')
        return
      }
      this.asrData = []
      this.voiceModel = ''
      // 加锁
      if(this.recordTransformData) return false
      console.log('正在打开录音组件')
      if(this.recIsOpen){
        if(asr) return this._realTimeAsrOpen()
        else return false
      }
      this.rec.open(success => {
        console.log('rec.open', success)
        this.recIsOpen = true
        if(this.recIsOpen){
          if(asr) return this._realTimeAsrOpen()
          else return false
        }
      }, (msg, isUserNotAllow) => {//用户拒绝未授权或不支持
          this.isAllow = isUserNotAllow
          console.log(msg + '&' + isUserNotAllow)
          this.$toast("请先打开麦克风");
      })
    },
    handlePoint (val) {
      this.isPoint = val
    },
    handleNext () {
      this.$router.push({
        path: '/composition/translates',
        query: {
          id: this.id,
          courseId: this.courseId,
          course_type: this.course_type
        }
      })
    },
    handleCloseModel () {
      this.isModel = false
    }
  },
}
</script>
<style lang="less" scoped>
// .content-wrap-box {
//   width: 640px;
//   overflow: hidden;
// }
.scene-box {
  height: calc(100% - 110px) !important;
  overflow-y: auto !important;
  overflow-x: hidden;
}
.content-des {
        .ask-title {
          font-size: 24px;
          font-family: Microsoft YaHei;
          font-weight: bold;
          color: #333;
          text-align: center;
          padding-top: 30px;
        }
        .info {
          font-size: 20px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #333;
          padding-top: 20px;
        }
      }
.main-box-item {
  // .content {
  //   overflow: auto;
  // }
  .content-wrap {
    position: relative;
    text-align: left;
    padding-top: 0;
    .work-title {
      padding-top: 30px;
    }
  }

}
.main-box-content {
  .content-wrap {
    position: relative;
    text-align: left;
    padding-top: 0;
    .work-title {
      padding-top: 30px;
    }
  .close {
        position: absolute;
        right: 20px;
        top: 2px;
        width: 20px;
        height: 20px;
        background: url(../../../assets/word/close-icon.png) no-repeat;
        background-size: 20px 20px;
        cursor: pointer;
        &:hover {
          background-image: url(../../../assets/word/close-hover.png);
        }
      }
    .model-title {
      font-size: 24px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #333;
      text-align: center;
      padding-top: 30px;
     }
     .model-info {
       font-size:20px;
       font-family:Microsoft YaHei;
       font-weight:400;
       color: #333;
       margin-top: 20px;
     }
  }
}
.record {
      position: absolute;
      left: 0;
      bottom: 0;
      display: flex;
      justify-content: center;
      width: 100%;
      height: 120px;
      text-align: center;
      background: #fff;
      opacity: .95;
      .first-item {
        margin-right: 90px;
      }
      &-item {
        cursor: pointer;
        img {
          width: 80px;
          height: 80px;
          margin-top: 10px;
          margin-bottom: -13px;
        }
        &-text {
          font-size: 16px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #27BFA3;
        }
      }
     }
// .scene-btn {
//     position: fixed;
//     left: 50%;
//     bottom: 30px;
//     transform: translateX(-50%);
//     display: flex;
//     justify-content: center;
//     align-items: center;
//     cursor: pointer;
//     span {
//       color: #27BFA3;
//       font-size: 20px;
//       font-family: Microsoft YaHei;
//       font-weight: 400;
//     }
//     img {
//       width: 40px;
//       height: 40px;
//       margin-left: 20px;
//     }
//   }
.buffer-wrap {
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  bottom: 20px;
  width: 100%;
  min-width: 1200px;
  z-index: 19;
}
  .buffer {
    position: absolute;
    left: 50%;
    bottom: -60px;
    transform: translateX(-50%);
    width: 600px;
    height: 250px;
    background: #E7F2EF;
    border-radius: 10px;
    margin: 0 auto;
    z-index: 20;
    &-desc {
      height: 130px;
      font-size:16px;
      font-family:Microsoft YaHei;
      font-weight:400;
      color: #333;
      text-align: left;
      padding: 30px 40px 14px;
      overflow: hidden;
      &-content {
        height: 100%;
        overflow: auto;
        &::-webkit-scrollbar { width: 0 !important }
      }
    }
    .bg-item {
      z-index: 2;
      span {
        background: #eee;
      }
    }
    .sec-item {
      z-index: 3
    }
    &-item {
      position: absolute;
      left: 50%;
      bottom: 65px;
      transform: translateX(-50%);
      display: flex;
      justify-content: center;
      align-items: flex-end;
      margin-bottom: 20px;
      margin-top: 20px;
      span {
        display: inline-block;
        width: 2px;
        height: 40px;
        background: #47CBB3;
        border-radius: 3px;
        margin-right: 3px;
        &:nth-child(1) {
          height: 20px;
        }
        &:nth-child(2) {
          height: 24px;
        }
        &:nth-child(3) {
          height: 28px;
        }
        &:nth-child(4) {
          height: 32px;
        }
        &:nth-child(5) {
          height: 36px;
        }
        &:nth-child(6) {
          height: 36px;
        }
        &:nth-child(7) {
          height: 32px;
        }
        &:nth-child(8) {
          height: 28px;
        }
        &:nth-child(9) {
          height: 24px;
        }
        &:nth-child(10) {
          height: 20px;
        }
      }
    }
    &-btn {
      position: fixed;
      left: 50%;
      bottom: 20px;
      transform: translateX(-50%);
      width: 200px;
      height: 46px;
      line-height: 46px;
      text-align: center;
      font-size:20px;
      font-family:Microsoft YaHei;
      font-weight:400;
      color: #fff;
      background:linear-gradient(360deg,rgba(71,203,179,1) 0%,rgba(81,211,176,1) 100%);
      box-shadow:0px 5px 10px rgba(59,201,164,0.3);
      border-radius: 100px;
    }
  }
</style>
